package com.yl.immodule.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.camera.routemodule.RouterPath;
import com.yl.immodule.R;
import com.yl.immodule.fragment.model.MessageListViewModel;
import com.yl.immodule.v.ChatMessageActivity;
import com.yl.immodule.util.TimeUtils;
import com.android.yl.ylicpsdk.ICPRtcManager;
import com.unionbroad.greendao.ChatMessage;
import com.unionbroad.greendao.MessageDialogue;

import java.util.ArrayList;
import java.util.List;

@Route(path = RouterPath.path.message_fragment)
public class MessageListFragment extends Fragment {

    private View rootView;
    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private MessageListViewModel viewModel;
    private MessageListAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.home_fragment_msg, container, false);
            recyclerView = rootView.findViewById(R.id.recyclerview);
            progressBar = rootView.findViewById(R.id.loading);

            // 初始化ViewModel
            viewModel = new ViewModelProvider(this).get(MessageListViewModel.class);

            // 初始化适配器
            adapter = new MessageListAdapter();
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            recyclerView.setAdapter(adapter);

            // 观察数据变化
            observeViewModel();
        }
        if (rootView.getParent() != null) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 刷新数据
        viewModel.loadConversations();
    }

    private void observeViewModel() {
        // 观察会话列表数据
        viewModel.dialogueList.observe(getViewLifecycleOwner(), dialogues -> {
            adapter.updateData(dialogues);
        });

        // 观察加载状态
        viewModel.isLoading.observe(getViewLifecycleOwner(), isLoading -> {
            progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        });
    }

    // 消息列表适配器
    private class MessageListAdapter extends RecyclerView.Adapter<MessageViewHolder> {

        private final List<MessageDialogue> dialogueList = new ArrayList<>();
        private final LayoutInflater inflater;

        MessageListAdapter() {
            inflater = LayoutInflater.from(getContext());
        }

        void updateData(List<MessageDialogue> newList) {
            dialogueList.clear();
            dialogueList.addAll(newList);
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = inflater.inflate(R.layout.item_messagelist, parent, false);
            return new MessageViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
            MessageDialogue dialogue = dialogueList.get(position);
            holder.bind(dialogue);
        }

        @Override
        public int getItemCount() {
            return dialogueList.size();
        }
    }

    // 消息视图持有者
    private class MessageViewHolder extends RecyclerView.ViewHolder {

        private final ImageView userIcon;
        private final TextView name;
        private final TextView message;
        private final TextView unreadTip;
        private final TextView type;
        private final TextView time;

        MessageViewHolder(View itemView) {
            super(itemView);
            userIcon = itemView.findViewById(R.id.user_icon);
            name = itemView.findViewById(R.id.name);
            message = itemView.findViewById(R.id.message);
            unreadTip = itemView.findViewById(R.id.unread_tip);
            type = itemView.findViewById(R.id.type);
            time = itemView.findViewById(R.id.time);
        }

        void bind(final MessageDialogue dialogue) {
            name.setText(dialogue.getName());

            // 设置头像
            if (!dialogue.getIsGroup()) {
                userIcon.setImageResource(R.drawable.ic_users_offline);
                type.setVisibility(View.GONE);
            } else {
                userIcon.setImageResource(R.drawable.re_default_custom_group);
                // 显示群聊标记
                type.setVisibility(View.VISIBLE);
                type.setText("群聊");
            }

            // 获取最后一条消息
            ChatMessage lastMessage = ICPRtcManager.getsInstance().getLastConversationMessage(dialogue.getChat_id());
            if (lastMessage != null) {
                // 设置消息预览
                message.setText(getMessagePreview(lastMessage));
                message.setVisibility(View.VISIBLE);
                
                // 设置时间
                time.setText(TimeUtils.formatTime(lastMessage.getTime_stamp()));
                time.setVisibility(View.VISIBLE);
            } else {
                message.setVisibility(View.GONE);
                time.setVisibility(View.GONE);
            }

            // 设置未读消息数
            int unReadCount = dialogue.getUnread();
            if (unReadCount <= 0) {
                unreadTip.setVisibility(View.GONE);
            } else {
                unreadTip.setVisibility(View.VISIBLE);
                if (unReadCount > 99) {
                    unreadTip.setText("99+");
                } else {
                    unreadTip.setText(String.valueOf(unReadCount));
                }
            }

            // 点击事件
            itemView.setOnClickListener(v -> {
                dialogue.setUnread(0);
                ICPRtcManager.getsInstance().markConversationAsRead(dialogue.getChat_id());
                adapter.notifyItemChanged(getAdapterPosition());
                ChatMessageActivity.show(getActivity(), dialogue.getChat_id());
            });

            // 长按删除
            itemView.setOnLongClickListener(v -> {
                showDeleteDialog(dialogue);
                return true;
            });
        }

        private String getMessagePreview(ChatMessage message) {
            switch (message.getCategory()) {
                case com.hm.poc.chat.ChatMessageCategory.TEXT:
                    return message.getText();
                case com.hm.poc.chat.ChatMessageCategory.AUDIO:
                    return "[语音呼叫]";
                case com.hm.poc.chat.ChatMessageCategory.VIDEO:
                    return "[视频呼叫]";
                case com.hm.poc.chat.ChatMessageCategory.IMAGE:
                    return "[图片]";
                case com.hm.poc.chat.ChatMessageCategory.AUDIO_FILE:
                case com.hm.poc.chat.ChatMessageCategory.PTT_AUDIO_FILE:
                    return "[语音]";
                default:
                    return "[未知消息]";
            }
        }
    }

    private void showDeleteDialog(MessageDialogue dialogue) {
        new AlertDialog.Builder(getContext())
                .setItems(new String[]{"删除对话"}, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            viewModel.deleteConversation(dialogue.getChat_id());
                            dialog.dismiss();
                        }
                    }
                }).create().show();
    }
}
